package raojt.day0109.tour.utils;


import java.sql.*;

public class BaseDao {
    protected static String driver;
    protected static String url;
    protected static String username;
    protected static String password;

    protected Connection conn;
    protected PreparedStatement pstmt;
    protected ResultSet rs;

    public Connection getConn() {
        driver = ConfigManager.getInstance().getProperty("oracle.driver");
        url = ConfigManager.getInstance().getProperty("oracle.url");
        username = ConfigManager.getInstance().getProperty("oracle.usernameTour");
        password = ConfigManager.getInstance().getProperty("oracle.password");

//        driver = "oracle.jdbc.driver.OracleDriver";
//        url = "jdbc:oracle:thin:@127.0.0.1:1522:orcl2";
//        username = "TRAVEL";
//        password = "m123";
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username,password);
        }catch (Exception e){
            e.printStackTrace();
        }
        return conn;
    }

    public void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs) {
        try {
            if (rs != null){
                rs.close();
            }
            if (pstmt != null){
                pstmt.close();
            }
            if (conn != null){
                conn.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    public ResultSet exectuteQuery(String sql,Object...params){
        conn = getConn();
        try{
            pstmt = conn.prepareStatement(sql);
            for(int i = 0;i<params.length;i++){
                pstmt.setObject(i+1,params[i]);
            }
            rs = pstmt.executeQuery();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return rs;
    }

    public int executeUpdate(String sql,Object...params){
        int UpdateRes = 0;
        conn = getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            for (int i = 0;i< params.length;i++){
                pstmt.setObject(i+1,params[i]);
            }
            UpdateRes = pstmt.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return UpdateRes;
    }
}